package org.idea.web.socket.manager;

import com.alibaba.fastjson.JSON;
import com.qiyu.core.cache.redis.client.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * socket管理器
 */
@Slf4j
@Component
public class SocketManager {

    @Resource
    private RedisService redisService;

    private static ConcurrentHashMap<String, WebSocketSession> manager = new ConcurrentHashMap<String, WebSocketSession>();

    public ConcurrentHashMap<String, WebSocketSession> getManager() {
        return manager;
    }

    public void add(String key, WebSocketSession webSocketSession) {
        log.info("新添加webSocket连接 {} ", key);
        manager.put(key, webSocketSession);
        redisService.setStr(key, "1", 9000, TimeUnit.SECONDS);
    }

    public void remove(String key) {
        log.info("移除webSocket连接 {} ", key);
        manager.remove(key);
        redisService.del(key);
    }

    public WebSocketSession get(String key) {
        log.info("获取webSocket连接 {}", key);
        String val = redisService.get(key);
        if (StringUtils.isNotEmpty(val)) {
            return manager.get(key);
        }
        return null;
    }


}
